﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VNPT;
using VNPT.Data;

namespace VNPT.DoiSoat
{
    public partial class uLayGTGT : Core.uBase
    {
        public uLayGTGT()
        {
            InitializeComponent();
        }
        public override void LoadSetting()
        {
            Load();
            base.LoadSetting();
        }
        private void Load()
        {
            btnLuu.Text = DoiSoatSetting.Folder_LUU;

        }
        private void Save()
        {
            DoiSoatSetting.Folder_LUU = btnLuu.Text;
        }
        public override void SaveSetting()
        {
            Save();
            base.SaveSetting();
        }
        public void AppendTextBox(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(AppendTextBox), new object[] { value });
                return;
            }
            memoEdit1.Text = value + Environment.NewLine + memoEdit1.Text;
        }
        private void SauKhiChay()
        {
            var m = this.Parent as DevExpress.XtraWizard.WizardPage;
            if (m != null)
            {
                m.AllowNext = true;
                m.AllowBack = true;
            }
        }


        private void TruocKhiChay()
        {
            var m = this.Parent as DevExpress.XtraWizard.WizardPage;
            if (m != null)
            {
                m.AllowNext = false;
                m.AllowBack = false;
            }

            DevExpress.XtraEditors.XtraForm f = null;
            if ((this.Parent as DevExpress.XtraEditors.XtraForm) != null)
            {
                f = this.Parent as DevExpress.XtraEditors.XtraForm;
            }
            else
            {
                if ((this.Parent.Parent as DevExpress.XtraEditors.XtraForm) != null)
                {
                    f = this.Parent.Parent as DevExpress.XtraEditors.XtraForm;
                }
                else
                {
                    if ((this.Parent.Parent.Parent as DevExpress.XtraEditors.XtraForm) != null)
                    {
                        f = this.Parent.Parent.Parent as DevExpress.XtraEditors.XtraForm;
                    }
                }

            }

            if (f != null)
            {
                f.FormClosing += (a1, e1) =>
                {
                    if (bgWork.IsBusy)
                    {
                        string text = "Chương trình đang chạy, không thể đóng form! Vui lòng hủy trước khi đóng chương trình?";
                        string caption = "Xác nhận?";
                        DevExpress.XtraEditors.XtraMessageBox.Show(text, caption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        e1.Cancel = true;
                    }
                };

            }
        }

        private void bgWork_DoWork(object sender, DoWorkEventArgs e)
        {
            RunExport();
        }

        string txt = "";
        private void bgWork_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            AppendTextBox(txt);
        }

        private void bgWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                AppendTextBox(e.Error.Message);
                DevExpress.XtraEditors.XtraMessageBox.Show("Hoàn thành, có phát sinh lỗi.\nVui lòng kiểm tra lại!\n"+e.Error.Message, "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Đã thành công!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                AppendTextBox("Hoàn thành!");
            }
            SauKhiChay();
        }

        private void bntCapNhat_Click(object sender, EventArgs e)
        {
            Save();
            TruocKhiChay();
            this.bgWork.RunWorkerAsync();
        }

        
        private void CreateTable(bool TableIn)
        {
            txt = string.Format("Connecting...");
            bgWork.ReportProgress(10);
            string SourceStr = string.Format(@"Provider=vfpoledb;Data Source={0};", DoiSoatSetting.Folder_LUU);

            string fileName = "##";
            if (TableIn)
            {
                fileName = string.Format("GTGTI_DLK_{0}{1:D2}_1", DoiSoatSetting.NAM, DoiSoatSetting.THANG);
            }
            else
            {
                fileName = string.Format("GTGTO_DLK_{0}{1:D2}_1", DoiSoatSetting.NAM, DoiSoatSetting.THANG);
            }
            var strSQL = string.Format(@"create table {0}
                                         (SO_CG     CHARACTER(22) NOT NULL,
                                          SO_BG     CHARACTER(22) NOT NULL,
                                          NGAY      DATE,
                                          GIOBD     CHARACTER(8) NOT NULL,
                                          TGLL      NUMERIC(10) NOT NULL,
                                          INC_ROUTE CHARACTER(10) NOT NULL,
                                          OUT_ROUTE CHARACTER(10) NOT NULL)", fileName);
            txt = string.Format("Create table {0}",fileName);
            bgWork.ReportProgress(100);
            using (var db= new DbNetData(SourceStr, DataProvider.OleDb))
            {
                db.Open();
                db.ExecuteQuery(new CommandConfig(strSQL));
            }
        }

        void ExportToDBF(bool TableIn)
        {
            string SourceStr = string.Format(@"Provider=vfpoledb;Data Source={0};", DoiSoatSetting.Folder_LUU);
            using (var DbFox = new DbNetData(SourceStr, DataProvider.OleDb))
            {
                DbFox.Open();
                    string fileName = "##";
                    string tbl_DVBB = string.Format("CT_DVBB_ALL_{0}_{1:D2}", DoiSoatSetting.NAM, DoiSoatSetting.THANG);
                    string sqlServer = "";
                    if (TableIn)// Dịch vụ in
                    {
                        sqlServer = string.Format(@"SELECT CHUGOI AS SO_CG, BIGOI AS SO_BG, NGAYBD as NGAY, GIOBD,
                                                                        TGGOI AS TGLL, INC_ROUTE, OUT_ROUTE , MA_MANG, DVBB  
                                                                        FROM DOISOAT.{0} 
                                                                        WHERE INC_ROUTE IN('VTELI') AND TGGOI > 2  
                                                                        AND SUBSTR(DVBB,1,5)  IN('DV108','DV801')", tbl_DVBB);

                        fileName = string.Format("GTGTI_DLK_{0}{1:D2}_1", DoiSoatSetting.NAM, DoiSoatSetting.THANG);
                    }
                    else
                    {
                        sqlServer = string.Format(@"SELECT CHUGOI AS SO_CG, BIGOI AS SO_BG, NGAYBD as NGAY, GIOBD, TGGOI AS TGLL, INC_ROUTE, OUT_ROUTE , MA_MANG, DVBB
                                    FROM doisoat.{0} WHERE SUBSTR(bigoi,1,3)  = '106'", tbl_DVBB);

                        fileName = string.Format("GTGTO_DLK_{0}{1:D2}_1", DoiSoatSetting.NAM, DoiSoatSetting.THANG);
                    }
                    QueryCommandConfig Query = new QueryCommandConfig(sqlServer);

                    DbServer.ExecuteQuery(Query);

                    
                    CommandConfig Insert = new CommandConfig(fileName);
                    while (DbServer.Reader.Read())
                    {
                        var m = DbServer.Reader;
                        var SO_CG = DbServer.Reader["SO_CG"];
                        var SO_BG = DbServer.Reader["SO_BG"];
                        var NGAY = DbServer.Reader["NGAY"];
                        var GIOBD = DbServer.Reader["GIOBD"];
                        var TGLL = DbServer.Reader["TGLL"];
                        var INC_ROUTE = DbServer.Reader["INC_ROUTE"];
                        var OUT_ROUTE = DbServer.Reader["OUT_ROUTE"];

                        Insert.Params["SO_CG"] = SO_CG;
                        Insert.Params["SO_BG"] = SO_BG;
                        Insert.Params["NGAY"] = NGAY;
                        Insert.Params["GIOBD"] = GIOBD;
                        Insert.Params["TGLL"] = TGLL;
                        Insert.Params["INC_ROUTE"] = INC_ROUTE;
                        Insert.Params["OUT_ROUTE"] = OUT_ROUTE;
                        DbFox.ExecuteInsert(Insert);
                    }
            }
        }

        void RunExport()
        {
            CreateTable(true);
            CreateTable(false);
            ExportToDBF(true);
            ExportToDBF(false);
        }
    }
}
